import { defineStore } from "pinia";
import { ref } from "vue";
import type { MqttClient } from "mqtt";
import * as mqtt from "mqtt";

interface MESSAGE {
  topic: string; // 消息的主题
  message: any; // 消息内容
}

const useMQTTStore = defineStore("mqtt", () => {
  const IS_Connect = ref(false); // 判断是否连接成功
  const Topics = ref([] as string[]); // 订阅的所有Topic
  const client = ref({} as MqttClient); // 连接MQTT后的实体
  const MQTT_HOST = ref(import.meta.env.VITE_GLOB_MQTT_URL); // 连接地址
  const MQTT_USERNAME = ref("MQTT_USERNAME"); // 可以为空
  const MQTT_PASSWORD = ref("MQTT_PASSWORD"); // 可以为空
  const CLIENT_ID = ref(""); // 连接MQTT的ID唯一标识
  const MQTT_MESSAGES = ref([] as MESSAGE[]); // MQTT订阅后收到的消息
  // 连接配置
  const options: any = {
    clientId: "",
    hostname: MQTT_HOST.value,
    protocol: "ws",
    protocolVersion: 4,
    port: 8083,
    path: "/mqtt",
    keepalive: 60,
    reconnectPeriod: 5,
    clean: true
  };
  // 连接
  function connect(clientId: string) {
		clientId += `_${new Date().getMilliseconds()}` // 生成唯一客户端id
    CLIENT_ID.value = clientId;
    return new Promise((resolve, reject) => {
      options.clientId = clientId;
      try {
        if (IS_Connect.value) return;
        client.value = mqtt.default.connect(options); // mqtt 的连接方法
        client.value?.on("connect", (res: any) => {
          // 连接上后执行方法
          IS_Connect.value = true;
        });
      } catch (error) {
        reject(error);
      }
    });
  }
  // 订阅
  function subscribe(topics: string[]) {
    // 订阅Topic 可以是多个，也可以是单个
    const new_topics: any = [];
    topics.forEach((topic: any) => {
      // 过滤一下已经订阅过的Topic
      if (!Topics.value.includes(topic)) {
        new_topics.push(topic);
        Topics.value.push(topic);
      }
    });
    client.value?.subscribe(new_topics); // 订阅新的Topic
    client.value?.on("message", receive); // 当消息抵达时
  }
  // 发布
  function sendPublic(topic: string, message: any) {
    client.value.publish(topic, JSON.stringify(message));
  }
  // 断开
  function disconnect() {
    IS_Connect.value && client.value.end();
    IS_Connect.value = false;
    Topics.value = [];
  }
  // 消息抵达
  function receive(topic: string, message: any) {
    // 场控数据，不做历史缓存
    MQTT_MESSAGES.value = [{
      // 消息加入接收消息数组
      topic,
      message: JSON.parse(message),
    }]


    // MQTT_MESSAGES.value.push({
    //   // 消息加入接收消息数组
    //   topic,
    //   message: JSON.parse(message),
    // });
  }
  return {
    // 暴露所有参数，可直接访问和修改
    IS_Connect,
    client,
    MQTT_HOST,
    MQTT_USERNAME,
    MQTT_PASSWORD,
    MQTT_MESSAGES,
    connect,
    subscribe,
    sendPublic,
    disconnect,
    receive,
  };
});
export default useMQTTStore;
